//
//  PopoverAnimator.swift
//  SwiftWeiBo
//
//  Created by wyw on 16/9/27.
//  Copyright © 2016年 Style_Y. All rights reserved.
//

import UIKit

// 通知
let YNotePopoverAnimatorWillShow = "YNotePopoverAnimatorWillShow"
let YNotePopoverAnimatorWillDissmiss = "YNotePopoverAnimatorWillDissmiss"

class PopoverAnimator: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning
{
    // 记录子菜单开启状态
    var isPresent : Bool = false
    
    var presentFrame = CGRect.zero
    
    // 实现代理方法，告诉谁来负责转场动画
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?
    {
        let pc = PoperPresentationController(presentedViewController: presented, presenting: presenting)
        pc.presentFrame = presentFrame
        return pc
    }
    
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YNotePopoverAnimatorWillShow), object: nil)
        isPresent = true
        return self;
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YNotePopoverAnimatorWillDissmiss), object: nil)
        isPresent = false
        return self;
    }
    
    // MARK: - UIViewControllerAnimatedTransitioning
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
    {
        return 0.5;
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning)
    {
        if isPresent {
            let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
            
            // 将视图添加到控制器上
            transitionContext.containerView.addSubview(toView!)
            
            // 设置锚点
            toView?.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0)
            
            toView?.transform = CGAffineTransform.init(scaleX: 1.0, y: 0)
            
            UIView .animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toView?.transform = CGAffineTransform.identity
            }) { (_) in
                // 动画执行完毕，一定要告诉系统
                transitionContext.completeTransition(true)
            }
        } else {
            let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                fromView?.transform = CGAffineTransform.init(scaleX: 1.0, y: 0.0000001)
                }, completion: { (_) in
                    transitionContext.completeTransition(true)
            })
            
        }
        
        
    }
}
